<route lang="json5" type="page">
{
  "needLogin": true,
  "style": {
    "navigationBarTitleText": "我的钱包",
  }
}
</route>

<script lang="ts" setup>
import { computed, ref } from 'vue'

// 交易记录的类型定义
interface Transaction {
  id: number
  type: 'electricity' | 'water' | 'recharge' | 'withdraw'
  description: string
  timestamp: string // ISO 格式时间戳
  amount: number
}

// 模拟数据
const balance = ref(2.90)
const weeklyElectricity = ref(122.12)
const weeklyWater = ref(122.12)

const dateRange = ref('thisWeek')
const dateRangeColumns = ref([
  { label: '今天', value: 'today' },
  { label: '本周', value: 'thisWeek' },
  { label: '本月', value: 'thisMonth' },
])
const dateRangeLabel = computed(() => {
  return dateRangeColumns.value.find(item => item.value === dateRange.value)?.label || ''
})
function onDateRangeConfirm({ value }: { value: string }) {
  dateRange.value = value
  uni.showToast({ title: '查询范围已切换', icon: 'none' })
}

// 格式化日期为 "M月d日"
function formatDate(date: Date): string {
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 根据选择动态计算日期范围显示
const dateRangeDisplay = computed(() => {
  const today = new Date()
  switch (dateRange.value) {
    case 'today':
      return formatDate(today)
    case 'thisWeek': {
      const dayOfWeek = today.getDay() // 0 = Sunday, 1 = Monday, ...
      const startOfWeek = new Date(today)
      const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1) // Adjust to Monday as start
      startOfWeek.setDate(diff)
      const endOfWeek = new Date(startOfWeek)
      endOfWeek.setDate(startOfWeek.getDate() + 6)
      return `${formatDate(startOfWeek)} - ${formatDate(endOfWeek)}`
    }
    case 'thisMonth': {
      const year = today.getFullYear()
      const month = today.getMonth()
      const firstDay = new Date(year, month, 1)
      const lastDay = new Date(year, month + 1, 0)
      return `${formatDate(firstDay)} - ${formatDate(lastDay)}`
    }
    default:
      return ''
  }
})

const transactions = ref<Transaction[]>([
  { id: 1, type: 'electricity', description: '电费 501电表', timestamp: '2023-07-14T14:03:00Z', amount: -29.15 },
  { id: 2, type: 'water', description: '水费 501水表', timestamp: '2023-07-14T13:50:00Z', amount: -20.17 },
  { id: 3, type: 'recharge', description: '充值', timestamp: '2023-07-14T10:42:00Z', amount: -18.40 }, // Assuming recharge can also be a payment for something
  { id: 4, type: 'withdraw', description: '提现', timestamp: '2023-07-14T10:03:00Z', amount: -29.15 },
  { id: 5, type: 'electricity', description: '电费 502电表', timestamp: '2023-07-14T09:11:00Z', amount: -29.15 },
  { id: 6, type: 'water', description: '水费 501水表', timestamp: '2023-07-14T08:33:00Z', amount: -29.15 },
  { id: 7, type: 'recharge', description: '充值', timestamp: '2023-07-14T08:15:00Z', amount: 2600.50 },
  { id: 8, type: 'recharge', description: '充值', timestamp: '2023-07-13T18:00:00Z', amount: 100.00 },
])

// 图标映射
const iconMap = {
  electricity: 'evaluation',
  water: 'evaluation',
  recharge: 'evaluation',
  withdraw: 'evaluation',
}

// 按日期对交易进行分组
const groupedTransactions = computed(() => {
  const groups: Record<string, Transaction[]> = {}
  transactions.value.forEach((tx) => {
    const date = new Date(tx.timestamp).toLocaleDateString('en-CA') // YYYY-MM-DD
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(tx)
  })
  return groups
})

// 格式化日期头部，例如 "14 July"
function formatDateHeader(dateString: string) {
  const date = new Date(dateString)
  return `${date.getDate()} ${date.toLocaleString('en-US', { month: 'short' })}`
}

// 格式化交易时间，例如 "02:03 PM"
function formatTime(timestamp: string) {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: true,
  })
}

/**
 * 1: 充值
 * 2: 提现
 * @param action 1: 充值 2: 提现
 */
function handleAction(action: 1 | 2) {
  uni.navigateTo({ url: action === 1 ? '/pages-user/user/wallet/recharge/index' : '/pages-user/user/wallet/withdraw/index' })
}
</script>

<template>
  <view class="wallet-page pb-6 pt-3">
    <!-- 自定义导航栏和余额卡片 -->
    <wd-card custom-class="balance-card">
      <view class="py-3">
        <view class="text-lg text-white">
          余额
        </view>
        <view class="mt-2 text-4xl text-white font-bold">
          ¥{{ balance.toFixed(2) }}
        </view>
        <view class="grid grid-cols-2 mt-8 gap-4">
          <wd-button block type="primary" @click="handleAction(1)">
            充值
          </wd-button>
          <wd-button block type="primary" @click="handleAction(2)">
            提现
          </wd-button>
        </view>
      </view>
    </wd-card>

    <!-- 本周账单 -->
    <view class="relative z-20 mt-3">
      <wd-card body-class="!p-0">
        <view class="py-4">
          <view class="flex items-center justify-between text-sm">
            <wd-picker
              v-model="dateRange"
              :columns="dateRangeColumns"
              use-default-slot
              @confirm="onDateRangeConfirm"
            >
              <view class="flex items-center text-blue-500 font-bold">
                <wd-icon name="arrow-down" />
                <text class="ml-1">
                  {{ dateRangeLabel }}
                </text>
              </view>
            </wd-picker>
            <view class="text-xs text-gray-400">
              {{ dateRangeDisplay }}
            </view>
          </view>
          <view class="grid grid-cols-2 mt-4 gap-4 text-center">
            <view>
              <view class="flex items-center justify-center text-gray-500">
                <wd-icon name="lightning-deal-fill" custom-class="!text-yellow-400" />
                <text class="ml-1">
                  电费
                </text>
              </view>
              <view class="mt-1 text-black font-bold">
                {{ weeklyElectricity.toFixed(2) }}元
              </view>
            </view>
            <view>
              <view class="flex items-center justify-center text-gray-500">
                <wd-icon name="safe-distance" custom-class="!text-blue-400" />
                <text class="ml-1">
                  水费
                </text>
              </view>
              <view class="mt-1 text-black font-bold">
                {{ weeklyWater.toFixed(2) }}元
              </view>
            </view>
          </view>
          <view class="mt-4 px-8">
            <wd-button block type="primary" size="small" @click="handleAction('区间查询')">
              区间查询
            </wd-button>
          </view>
        </view>
      </wd-card>
    </view>

    <!-- 交易记录 -->
    <view class="mt-3">
      <wd-card custom-class="!p-0">
        <view v-for="(group, date) in groupedTransactions" :key="date" class="transaction-group pt-2">
          <view class="flex items-center justify-between px-4 py-2 text-sm text-gray-500">
            <text>{{ formatDateHeader(date) }}</text>
          </view>
          <view>
            <view v-for="tx in group" :key="tx.id" class="flex items-center border-t border-gray-100 px-4 py-3">
              <wd-icon :name="iconMap[tx.type]" size="36rpx" />
              <view class="ml-3 flex-1">
                {{ tx.description }}
              </view>
              <view class="text-right">
                <view class="text-xs text-gray-400">
                  {{ formatTime(tx.timestamp) }}
                </view>
                <view
                  class="font-bold"
                  :class="[tx.amount > 0 ? 'text-green-500' : 'text-red-500']"
                >
                  {{ tx.amount > 0 ? '+' : '' }}{{ tx.amount.toFixed(2).replace(',', '.') }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </wd-card>
    </view>
  </view>
</template>

<style lang="scss" scoped>
 :deep(.balance-card) {
  background: linear-gradient(to bottom, #5252ff 0%, #5252ff 100%);
}
</style>
